const Controller = require('egg').Controller;

function toInt(str) {
    if (typeof str === 'number') return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
}

const createRule = {
    userName: {
        type: 'string',
    },
    password: {
        type: 'string',
    },
};


class UserController extends Controller {

    async getMunu() {
        const ctx = this.ctx;

        ctx.body = {
            uid: 1,
            token: '11111',
            name: "Jerry"
        }
    }
    async getUserInfo() {

        this.ctx.body = {
            uid: 1,
            token: '11111',

            name: "Jerry"
        }
    }



    async index() {
        const ctx = this.ctx;
        let token = ctx.cookies.get('token', { signed: true, });
        let uid = ctx.cookies.get('uid', { signed: true, });

        let decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        if (decode.id == uid) {
            // 过 Service 获取用户信息
        }
        ctx.body = decode;
    }

    async show() {
        const { ctx, app } = this;
        const res = {};
        ctx.validate(createRule);
        var where = {
            ...ctx.request.body
        };
        var data = await ctx.model.User.findOne({
            where: where
        });
        if (data) {
            let signData = {
                id: data.id
            }
            const token = app.jwt.sign({ ...signData }, app.config.jwt.secret, { expiresIn: app.config.jwt.expiresIn });
            res.code = 200;
            res.data = token;
            res.msg = '获取成功';
            ctx.cookies.set('token', token);
            ctx.cookies.set('uid', data.id);
        } else {
            res.code = 201;
            res.msg = '账号或者密码错误';
        }
        ctx.body = res
    }

    async create() {
        const ctx = this.ctx;
        const user = await ctx.model.User.create({ userName: "admin", password: "admin" });
        ctx.status = 201;
        ctx.body = user;
    }

    async update() {
        const ctx = this.ctx;
        const id = toInt(ctx.params.id);
        const user = await ctx.model.User.findByPk(id);
        if (!user) {
            ctx.status = 404;
            return;
        }

        const { name, age } = ctx.request.body;
        await user.update({ name, age });
        ctx.body = user;
    }

    async destroy() {
        const ctx = this.ctx;
        const id = toInt(ctx.params.id);
        const user = await ctx.model.User.findByPk(id);
        if (!user) {
            ctx.status = 404;
            return;
        }

        await user.destroy();
        ctx.status = 200;
    }


    async getlist(){
        const ctx = this.ctx;
        var data = await ctx.model.User.findAll();
        ctx.body =data
    }
}

module.exports = UserController;